<template>
  <!-- 新增 修改 详情 -->
  <el-dialog
    width="800px"
    :title="title"
    destroy-on-close
    append-to-body
    :visible.sync="show"
    :before-close="cancel">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      size="small"
      label-width="150px"
      :disabled="type == 'detail'">
      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="distrName">
            <el-input v-model="form.distrName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商地址" prop="address">
            <el-input v-model="form.address" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商电话" prop="tel">
            <el-input v-model="form.tel" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商微信" prop="wechat">
            <el-input v-model="form.wechat" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商负责人" prop="responsibleUser">
            <el-input v-model="form.responsibleUser" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商负责人电话" prop="responsibleTel">
            <el-input v-model="form.responsibleTel" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商手续费" prop="handlingFee">
            <el-input-number
              style="width: 100%"
              v-model="form.handlingFee"
              controls-position="right"
              :min="0"></el-input-number>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商级别" prop="level">
            <el-select style="width: 100%" v-model="form.level" :placeholder="$t('请选择')">
              <el-option label="一级" :value="1" />
              <el-option label="二级" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="供应商邮箱" prop="email">
            <el-input v-model="form.email" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="供应商oicq" prop="oicq">
            <el-input v-model="form.oicq" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12" v-if="type == 'add'">
          <el-form-item label="密码" prop="password">
            <el-input v-model="form.password" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12" v-if="type == 'add'">
          <el-form-item label="云审批自动通过" prop="autoVerify">
            <el-switch v-model="form.autoVerify" :active-value="1" :inactive-value="0"> </el-switch>
          </el-form-item>
        </el-col> -->

        <!-- <el-col :span="12">
            <el-form-item label="供应商利润倍率" prop="profitRate">
              <el-input type="number" v-model.number="form.profitRate" />
            </el-form-item>
          </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="供应商营业时间" prop="operateTime">
            <el-time-picker
              value-format="HH:mm:ss"
              format="HH:mm:ss"
              style="width: 100%"
              is-range
              v-model="form.operateTime" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" :rows="4" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding: 10px 0">
        <el-form-item label="推荐人:" prop="referrerId">
          <el-select
            @change="handleReferrerId"
            @clear="handleReferrerIdClear"
            clearable
            filterable
            style="width: 100%"
            v-model="form.referrerId">
            <el-option
              :label="item.name || item.distrName"
              :value="item.distrId"
              :key="item.distrId"
              v-for="item in distributorList" />
          </el-select>
        </el-form-item>
        <el-form-item label="推荐人上级:">
          <el-select disabled filterable style="width: 100%" v-model="form.referrerSuperId">
            <el-option
              :label="item.name || item.distrName"
              :value="item.distrId"
              :key="item.distrId"
              v-for="item in distributorList" />
          </el-select>
        </el-form-item>
        <!-- 推荐人 校验 -->
        <el-form-item label="推荐人:" prop="referrerProportion" v-if="form.referrerId" key="referrerId1">
          <el-input type="number" v-model.number="form.referrerProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <!-- 推荐人 不校验 -->
        <el-form-item label="推荐人:" v-if="!form.referrerId" key="referrerId2">
          <el-input type="number" v-model.number="form.referrerProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <!-- 推荐人上级 校验 -->
        <el-form-item
          label="推荐人上级:"
          v-if="form.referrerSuperId"
          key="referrerSuperId1"
          prop="referrerSuperProportion">
          <el-input
            :disabled="!form.referrerSuperId"
            type="number"
            v-model.number="form.referrerSuperProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <!-- 推荐人上级 不校验 -->
        <el-form-item v-if="!form.referrerSuperId" label="推荐人上级:" key="referrerSuperId2">
          <el-input
            :disabled="!form.referrerSuperId"
            type="number"
            v-model.number="form.referrerSuperProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="总公司:" prop="headOfficeProportion">
          <el-input type="number" v-model.number="form.headOfficeProportion">
            <el-button slot="prepend"> 比例 </el-button>
            <el-button slot="append">%</el-button>
          </el-input>
        </el-form-item>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" v-if="type != 'detail'" @click="handleSubmit"> 确 定 </el-button>
      <el-button @click="cancel">关 闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { getReferrerRegisterDistributor } from '@/api/platform/supplierManage'

import {
  getDistributorList,
  insertDistributorUser,
  updateDistributorUser,
} from '@/api/platform/supplierManage'

export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  props: {
    /**
     * formData
     */
    formData: {
      type: Object,
      default: () => ({}),
    },
    /**
     * type
     */
    type: {
      type: String,
      default: 'add',
    },
    /**
     * 控制显示隐藏
     */
    show: {
      type: Boolean,
      required: true,
      default: false,
    },
  },
  data() {
    return {
      distributorList: [],
      form: {
        autoVerify: 0,
        applyRestrict: 0,
        type: 2,
        referrerProportion: '',
        referrerSuperProportion: '',
        headOfficeProportion: 100,
      },
      // 表单校验
      rules: {
        distrName: [{ required: true, message: '请输入', trigger: 'blur' }],
        address: [{ required: true, message: '请输入', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入', trigger: 'blur' }],
        applyRestrict: [{ required: true, message: '请选择', trigger: 'blur' }],
        autoVerify: [{ required: true, message: '请选择', trigger: 'blur' }],
        responsibleUser: [{ required: true, message: '请输入', trigger: 'blur' }],
        responsibleTel: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateStartTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        operateEndTime: [{ required: true, message: '请输入', trigger: 'blur' }],
        email: [
          {
            type: 'email',
            required: true,
            message: '请输入正确的邮箱地址',
            trigger: 'blur',
          },
        ],
        password: [{ required: true, message: '请输入', trigger: 'blur' }],
        profitRate: [{ required: true, message: '请输入', trigger: 'blur' }],
        empty: [],
        referrerProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        referrerSuperProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        headOfficeProportion: [
          {
            validator: this.valid,
            required: true,
            trigger: 'blur',
          },
        ],
        // handlingFee: [{ required: true, message: '请输入', trigger: 'blur' }],
        level: [{ required: true, message: '请输入', trigger: 'blur' }],
        type: [{ required: true, message: '请输入', trigger: 'blur' }],
        // remark: [{ required: true, message: '请输入', trigger: 'blur' }],
      },
    }
  },
  computed: {
    title() {
      if (this.type == 'add') {
        return this.$t('添加')
      }
      if (this.type == 'edit') {
        return this.$t('编辑')
      }
      if (this.type == 'detail') {
        return this.$t('详情')
      }
    },
  },
  watch: {
    show: function (newValue) {
      if (newValue) {
        this.resetForm()

        if (this.type == 'add') {
          this.form.distributorList = []
          this.distributorList = []
          // this.form.autoVerify = 1
          getDistributorList().then((res) => {
            console.log(`res ==>`, res)
            const { code, data, msg } = res
            if (code === 200) {
              this.distributorList = res.data
            }
          })
        }
        if (this.type == 'edit' || this.type == 'detail') {
          Object.keys(this.formData).forEach((key) => {
            this.$set(this.form, key, this.formData[key])
          })
          this.form.operateTime = this.form.operateTime?.split('-').map((i) => {
            return i.length == 5 ? i + ':00' : i
          })
          this.distributorList = this.formData.distributorList

          console.log(`this.form ==>`, JSON.parse(JSON.stringify(this.form)))
        }
      }
    },
  },
  methods: {
    handleReferrerIdClear() {
      this.form.referrerSuperId = null
      this.form.referrerProportion = null
      this.form.referrerSuperProportion = null
      this.form.headOfficeProportion = 100
    },
    handleReferrerId(distrId) {
      this.form.referrerSuperProportion = null
      if (!distrId) return
      console.log(`distrId ==>`, JSON.parse(JSON.stringify(distrId)))
      getReferrerRegisterDistributor({
        distrId,
      }).then((res) => {
        this.form.referrerSuperId = res.data.distrId
      })
    },
    /**验证推荐人 */
    valid(rule, value, callback) {
      console.log(`rule, value, ==>`, JSON.parse(JSON.stringify({ rule, value })))
      const { field } = rule
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form

      if (String(value).trim() == '') {
        return callback(new Error('请输入'))
      }

      if (field == 'referrerProportion' /**推荐人 */) {
        if (+referrerProportion > 100 || +referrerProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      if (field == 'referrerSuperProportion' /**推荐人上级 */) {
        if (+referrerSuperProportion > 100 || +referrerSuperProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      if (field == 'headOfficeProportion' /**总公司 */) {
        if (+headOfficeProportion > 100 || +headOfficeProportion < 0) {
          return callback(new Error('取值范围在0~100'))
        }
      }

      const total = +referrerProportion + +referrerSuperProportion + +headOfficeProportion

      if (total > 100) {
        callback(new Error('总和不能超过100'))
      }
      return callback()
    },

    handleSubmit() {
      // 判断分成相加是否为100
      const {
        /** 推荐人*/
        referrerProportion,
        /** 推荐人上级*/
        referrerSuperProportion,
        /** 总公司*/
        headOfficeProportion,
      } = this.form
      const total = +referrerProportion + +referrerSuperProportion + +headOfficeProportion

      if (total != 100) {
        return this.$message.error('比例总和必须为100')
      }

      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const data = JSON.parse(JSON.stringify(this.form))
          data.operateTime = data.operateTime?.join('-')
          if (this.type == 'add') {
            insertDistributorUser(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })

                this.cancel()
                this.$emit('getList')
              }
            })
          } else {
            updateDistributorUser(data).then((res) => {
              const { code, data, msg } = res
              if (code === 200) {
                this.$message({ type: 'success', message: msg })

                this.cancel()
                this.$emit('getList')
              }
            })
          }
        }
      })
    },
    resetForm() {
      Object.keys(this.form).forEach((key) => (this.form[key] = ''))
    },

    cancel() {
      this.$emit('update:show', false)
    },
  },
}
</script>
<style scoped lang="scss"></style>
